package cn.yuxiaoyuan.config;

import cn.yuxiaoyuan.util.JwtUtil;
import cn.yuxiaoyuan.util.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token != null){
            try {
                JwtUtil.parseJwtToken(token);
                return true;
            }catch (Exception e){
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"code\":900,\"message\":\"toLogin\"}");
                return false;
            }
        }
        //3.1.为null=没有登录或过期了=>想办法跳转登录页面
        //response.sendRedirect("http://localhost:8081/#/login"); - 万一是用户访问
        //告诉浏览器我要给你响应一个json数据[自动将json格式的字符串-json对象]
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"code\":900,\"message\":\"toLogin\"}");
        return false;
    }
}
